package com.xh.bussiness.jingyou.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.jingyou.constants.JingYouConstants;
import com.xh.bussiness.jingyou.dao.JYUserInterfaceLastMapper;
import com.xh.bussiness.jingyou.model.JYUserInterfaceLast;
import com.xh.bussiness.jingyou.utils.DES3;
import com.xh.bussiness.jingyou.utils.Utility;
import com.xh.core.properties.XhProperties;
import com.xh.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xh.bussiness.jingyou.dao.JYUserMapper;
import com.xh.bussiness.jingyou.model.JYUser;
import com.xh.bussiness.jingyou.service.IJYUserService;
import com.xh.core.service.impl.BaseServiceImpl;

/**
 * <p>
 * 菁优网用户 服务实现类
 * </p>
 *
 * @author JQM
 * @since 2019-11-11
 */
@Service
public class JYUserServiceImpl extends BaseServiceImpl<JYUserMapper, JYUser> implements IJYUserService {

	@Autowired
	private JYUserInterfaceLastMapper jYUserInterfaceLastMapper;
	@Autowired
	private XhProperties xhProperties;

	@Override
	public JYUser getAvailableUser(Integer type) {
        String jyAccountPrefix = xhProperties.getJyAccountPrefix();
        List<JYUserInterfaceLast> jyUserInterfaceLastList = jYUserInterfaceLastMapper.queryAvailableUser(type, jyAccountPrefix);
		if(jyUserInterfaceLastList!=null&&jyUserInterfaceLastList.size()>0){
			JYUserInterfaceLast jyUserInterfaceLast=jyUserInterfaceLastList.get(0);
			//账号使用数扣减
			Integer uc=jYUserInterfaceLastMapper.updateUserInterfaceLastCount(jyUserInterfaceLast.getJyUserId(),jyUserInterfaceLast.getJyInterface());
			if(uc<=0){
				return getAvailableUser(type);
			}
			return this.getById(jyUserInterfaceLast.getJyUserId());
		}else{
			//新增账号
			synchronized(jyUserInterfaceLastList){
                jyUserInterfaceLastList=jYUserInterfaceLastMapper.queryAvailableUser(type,jyAccountPrefix);
				if(jyUserInterfaceLastList!=null&&jyUserInterfaceLastList.size()>0){
					JYUserInterfaceLast jyUserInterfaceLast=jyUserInterfaceLastList.get(0);
					//账号使用数扣减
					Integer uc=jYUserInterfaceLastMapper.updateUserInterfaceLastCount(jyUserInterfaceLast.getJyUserId(),jyUserInterfaceLast.getJyInterface());
					if(uc<=0){
						return getAvailableUser(type);
					}
					return this.getById(jyUserInterfaceLast.getJyUserId());
				}
				return createAccount(type);
			}
		}
	}

	private JYUser createAccount(Integer type){
		String account = "LW";
		SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMdd");
		Date d= new Date();
		account += sdf.format(d);
		int random=(int)(Math.random()*900)+100;
		account+=random;
		JYUser user = new JYUser();
		boolean flag=false;
		try{
            String userType = xhProperties.getJyAccountPrefix();
            user.setName("龙文用户");
			user.setAccount(account);
			user.setRole(1);
			user.setPassword(account);
			user.setSchool("龙文教育");
			user.setSex(1);
            user.setUserType(userType);
			JSONObject jo = new JSONObject();

			jo.put("ApiID", JingYouConstants.ACCOUNT_API_ID);
			jo.put("ApiPwd", JingYouConstants.ACCOUNT_API_PWD);
			jo.put("School", user.getSchool());
			jo.put("UserID", user.getAccount());
			jo.put("UserPwd", user.getPassword());
			jo.put("UserName", user.getName());
			jo.put("UserRole", user.getRole());
			jo.put("UserSex", user.getSex());

			String json = jo.toString();
			String eson = DES3.encrypt(json,JingYouConstants.ACCOUNT_API_KEY);

			String url = String.format("http://api.jyeoo.com/v1/register?id=%s&v=%s", JingYouConstants.ACCOUNT_API_ID, eson);
			String userId = Utility.sendPost(null, url, String.class);
			if(!StringUtils.isEmpty(userId)){
				user.setId(userId);
				flag=this.insert(user);
				if(flag){
					flag=createAllUserInterface(user.getId());
				}
			}
		}catch (Exception ex){

		}
		if(flag){
			jYUserInterfaceLastMapper.updateUserInterfaceLastCount(user.getAccount(),type);
			return user;
		}else{
			return createAccount(type);
		}
	}

	private boolean createAllUserInterface(String userId){
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_QUESTION_QUERY_ANALYSIS,JingYouConstants.INTERFACE_LIMIT_QUESTION_QUERY_ANALYSIS);
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_QUESTION_QUERY_BY_KEY,JingYouConstants.INTERFACE_LIMIT_QUESTION_QUERY_BY_KEY);
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_QUESTION_QUERY_BY_PAGE,JingYouConstants.INTERFACE_LIMIT_QUESTION_QUERY_BY_PAGE);
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_QUESTION_QUERY_BY_IMG,JingYouConstants.INTERFACE_LIMIT_QUESTION_QUERY_BY_IMG);
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_QUESTION_DOWN,JingYouConstants.INTERFACE_LIMIT_QUESTION_DOWN);
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_QUESTION_RECOMMOND,JingYouConstants.INTERFACE_LIMIT_QUESTION_RECOMMOND);
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_QUESTION_QUERY_TITLES,JingYouConstants.INTERFACE_LIMIT_QUESTION_QUERY_TITLES);
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_PAPER_QUERY_BY_PAGE,JingYouConstants.INTERFACE_LIMIT_PAPER_QUERY_BY_PAGE);
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_PAPER_DOWN,JingYouConstants.INTERFACE_LIMIT_PAPER_DOWN);
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_PAPER_SUBMIT,JingYouConstants.INTERFACE_LIMIT_PAPER_SUBMIT);
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_PAPER_QUERY_BY_ID,JingYouConstants.INTERFACE_LIMIT_PAPER_QUERY_BY_ID);
		createUserInterface(userId,JingYouConstants.INTERFACE_PAPER_QUERY_ANALYSIS,JingYouConstants.INTERFACE_LIMIT_PAPER_QUERY_ANALYSIS);
		createUserInterface(userId,JingYouConstants.INTERFACE_TYPE_PAPER_SMART_PAPER,JingYouConstants.INTERFACE_LIMIT_PAPER_SMART_PAPER);
		return true;
	}

	private boolean createUserInterface(String userId,Integer interfaceType,Integer totalCount){
		JYUserInterfaceLast jyUserInterfaceLast=new JYUserInterfaceLast();
		jyUserInterfaceLast.setJyUserId(userId);
		jyUserInterfaceLast.setJyInterface(interfaceType);
		jyUserInterfaceLast.setLastCount(totalCount);
		jyUserInterfaceLast.setTotalCount(totalCount);
		jYUserInterfaceLastMapper.insert(jyUserInterfaceLast);
		return true;
	}
}
